import Vue from 'vue'
import {isArr} from "@/utils/arrayUtil";
import guid from "@/utils/guid";

const state = {
  temporaryFileList: [
    {
      uid:`file_${guid()}`,
      fileList:[]
    }
  ],
}

const mutations = {
  SET_FILE_LIST: (state, {uid, file}) => {
    let currentFileListItem = _.find(state.temporaryFileList, item => item.uid == uid);
    if (currentFileListItem) {
      let index = _.findIndex(state.temporaryFileList, item => item.uid == uid);
      currentFileListItem.fileList.push(file)
      Vue.set(state.temporaryFileList, index, currentFileListItem)
    } else {
      currentFileListItem = {uid, fileList: [file]};
      state.temporaryFileList.push(currentFileListItem)
    }
  },
  REMOVE_FILE(state, {uid, file}) {
    let currentFileListItem = _.find(state.temporaryFileList, item => item.uid == uid);
    if (!currentFileListItem || !isArr(currentFileListItem.fileList) || !_.some(currentFileListItem.fileList, item => item.fileId == file.fileId)) {
      return
    }
    currentFileListItem.fileList = _.filter(currentFileListItem.fileList, item => item.fileId != file.fileId)
    let index = _.findIndex(state.temporaryFileList, item => item.uid == uid);
    Vue.set(state.temporaryFileList, index, currentFileListItem)
  },
  REMOVE_ALL_FILE(state, uid) {
    let currentFileListItem = _.find(state.temporaryFileList, item => item.uid == uid);
    if (!currentFileListItem || !isArr(currentFileListItem.fileList)) {
      return
    }
    currentFileListItem.fileList = []
    let index = _.findIndex(state.temporaryFileList, item => item.uid == uid);
    Vue.set(state.temporaryFileList, index, currentFileListItem)
  }
}
const actions = {
  addDoc({dispatch, commit}, param) {
    return new Promise((resolve, reject) => {
      let {uid, fileId, fileName, fileUrl} = param
      commit('SET_FILE_LIST', {uid, file: {fileId, fileName, fileUrl}})
      resolve()
    })
  },
  addDocList({dispatch, commit}, param){
    return new Promise((resolve, reject) => {
      let {uid,fileList} = param
      if (!isArr(fileList)){
        resolve()
        return
      }
      fileList.forEach(file => {
        let {fileId, fileName, fileUrl} = file
        commit('SET_FILE_LIST', {uid, file: {fileId, fileName, fileUrl}})
      })
      resolve()
    });
  },
  removeProjectDoc({dispatch, commit}, param) {
    return new Promise((resolve, reject) => {
      let {uid, fileId, fileName, fileUrl} = param
      commit('REMOVE_FILE', {uid, file: {fileId, fileName, fileUrl}})
      resolve()
    })
  },
}
export default {
  namespaced: true, state, mutations, actions
}
